package com.aplink.generic;

import java.io.IOException;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.aplink.generic.adapter.NavigationDrawerAdapter;
import com.aplink.generic.autosync.SyncUtils;
import com.aplink.generic.bitmap.ImageFetcher;
import com.aplink.generic.controller.GenericApplication;
import com.aplink.generic.pojo.MainMenu;
import com.aplink.generic.pojo.MainMenuItem;
import com.aplink.generic.pojo.formdesign.FormDesign;
import com.aplink.generic.sharepreference.GenericSharePreference;
import com.aplink.generic.util.DatabaseBackup;
import com.aplink.generic.xmlparser.FormDesignParser;
import com.aplink.sg.BuildConfig;
import com.aplink.sg.R;

public abstract class GenericActivity extends FragmentActivity {
	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		
		@Override
		public void onItemClick(final AdapterView<?> parent, final View view,
				final int position, final long id) {
			final MainMenuItem mainMenuItem = GenericActivity.this.mDrawerAdapter
					.getItem(position);
			if (!TextUtils.isEmpty(mainMenuItem.getActivityName())) {
				final Class<?> targetClass = GenericApplication.getInstance()
						.getTargetActivity(mainMenuItem.getActivityName());
				if (targetClass != null) {
					final Intent intent = new Intent(getApplicationContext(),
							targetClass);
					GenericActivity.this.startActivity(intent);
					GenericActivity.this.mDrawerLayout
							.closeDrawer(GenericActivity.this.mDrawerList);
				}
			}
		}
	}
	
	public static final int NONE = 0;
	private final long delayMillis = 5000;
	private NavigationDrawerAdapter mDrawerAdapter;
	protected DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private CharSequence mDrawerTitle;
	private ActionBarDrawerToggle mDrawerToggle;
	private FormDesign mFormDesign;
	private GenericFragment mGenericFragment = null;
	private ImageFetcher mImageFetcher;
	
	protected Resources mResources;
	
	private CharSequence mTitle;
	
	private final Runnable startAutoSync = new Runnable() {
		
		@Override
		public void run() {
			GenericSharePreference.getInstance().setStartAutoSync(true);
		}
	};
	
	protected void afterCreateFragment() {
		
	}
	
	protected void beforeCreateFragment() {
		
	}
	
	public ListView getListMenuItem() {
		return this.mDrawerList;
	}
	
	private void handleAutoSync() {
		if (!GenericSharePreference.getInstance().isSetUpAccountComplete()) {
			SyncUtils.getInstance().CreateSyncAccount();
		}
		if (GenericSharePreference.getInstance().isEnableAutoSync()) {
			GenericSharePreference.getInstance().setStartAutoSync(false);
			SyncUtils.getInstance().enableAutoSync();
		}
	}
	
	private void handleIntent(final Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			final String query = intent.getStringExtra(SearchManager.QUERY);
			if (this.mGenericFragment.getOnSearchListener() != null) {
				this.mGenericFragment.getOnSearchListener().onSearch(
						mGenericFragment.getFormDesign().getActionBar()
								.getSearchViewSpec().getSearchFileds(), query);
			}
		}
		
	}
	
	protected abstract int initContentData();
	
	protected abstract int initFormDesign();
	
	@Override
	public void onBackPressed() {
		if (this.mGenericFragment != null) {
			this.mGenericFragment.onBackPressed();
		}
	}
	
	@Override
	public void onConfigurationChanged(final Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (this.mDrawerToggle != null) {
			this.mDrawerToggle.onConfigurationChanged(newConfig);
		}
	}
	
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		handleAutoSync();
		beforeCreateFragment();
		mFormDesign = FormDesignParser.getInstance().parse(initFormDesign());
		handleActionBar();
		this.mGenericFragment = GenericFragment.newInstance(initFormDesign(),
				initContentData());
		if (mFormDesign.isEnableNavigateDrawer()
				&& (GenericApplication.getInstance().getMainMenu() != null)) {
			final MainMenu mainMenu = GenericApplication.getInstance()
					.getMainMenu();
			if (this.mGenericFragment != null) {
				final FragmentManager fragmentManager = getSupportFragmentManager();
				final FragmentTransaction fragmentTransaction = fragmentManager
						.beginTransaction();
				fragmentTransaction.addToBackStack(this.getClass()
						.getSimpleName());
				fragmentTransaction.replace(R.id.content_frame,
						this.mGenericFragment, this.getClass().getSimpleName());
				fragmentTransaction.commit();
				
				this.mImageFetcher = this.mGenericFragment.getImageFetcher();
			}
			this.setContentView(R.layout.aplink__generic_navigate_drawner);
			this.mTitle = this.mDrawerTitle = getTitle();
			this.mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
			this.mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
					GravityCompat.START);
			if (mFormDesign.hasActionBar()
					&& !mFormDesign.getActionBar().isDisplayHomeAsUp()) {
				this.mDrawerToggle = new ActionBarDrawerToggle(this,
						this.mDrawerLayout, R.drawable.ic_drawer,
						R.string.drawer_open, R.string.drawer_close) {
					@Override
					public void onDrawerClosed(final View view) {
						GenericActivity.this.getActionBar().setTitle(
								GenericActivity.this.mTitle);
						GenericActivity.this.invalidateOptionsMenu();
					}
					
					@Override
					public void onDrawerOpened(final View drawerView) {
						final ActionBar actionBar = GenericActivity.this
								.getActionBar();
						if (actionBar != null) {
							GenericActivity.this.getActionBar().setTitle(
									GenericActivity.this.mDrawerTitle);
							GenericActivity.this.invalidateOptionsMenu();
						}
					}
				};
				this.mDrawerLayout.setDrawerListener(this.mDrawerToggle);
			}
			this.mDrawerAdapter = new NavigationDrawerAdapter(this, mainMenu);
			this.mDrawerList = (ListView) findViewById(R.id.left_drawer);
			this.mDrawerList.setAdapter(this.mDrawerAdapter);
			this.mDrawerList
					.setOnItemClickListener(new DrawerItemClickListener());
		} else {
			final FragmentManager fragmentManager = getSupportFragmentManager();
			final FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			fragmentTransaction.addToBackStack(this.getClass().getSimpleName());
			fragmentTransaction.replace(android.R.id.content,
					this.mGenericFragment, this.getClass().getSimpleName());
			fragmentTransaction.commit();
			this.mImageFetcher = this.mGenericFragment.getImageFetcher();
		}
	}
	
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private void handleActionBar() {
		if (!mFormDesign.hasActionBar()) {
			if (getActionBar() != null) {
				getActionBar().hide();
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (this.mImageFetcher != null) {
			this.mImageFetcher.closeCache();
		}
	}
	
	@Override
	protected void onNewIntent(final Intent intent) {
		setIntent(intent);
		handleIntent(intent);
	}
	
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		if (mDrawerToggle != null) {
			if (this.mDrawerToggle.onOptionsItemSelected(item)) {
				return true;
			}
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (GenericSharePreference.getInstance().isEnableAutoSync()) {
			new Handler().postDelayed(this.startAutoSync, this.delayMillis);
		}
		
		if (this.mImageFetcher != null) {
			this.mImageFetcher.setExitTasksEarly(true);
			this.mImageFetcher.flushCache();
		}
	}
	
	@Override
	protected void onPostCreate(final Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		if (this.mDrawerToggle != null) {
			this.mDrawerToggle.syncState();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (GenericSharePreference.getInstance().isEnableAutoSync()) {
			GenericSharePreference.getInstance().setStartAutoSync(false);
		}
		if (BuildConfig.DEBUG) {
			final DatabaseBackup backup = new DatabaseBackup();
			try {
				backup.writeToSD(getApplicationContext());
			} catch (final IOException e) {
				e.printStackTrace();
			}
		}
		if (this.mImageFetcher != null) {
			this.mImageFetcher.setExitTasksEarly(false);
		}
	}
	
	public void setListMenuItem(final ListView listMenuItem) {
		this.mDrawerList = listMenuItem;
	}
	
	@Override
	public void setTitle(final CharSequence title) {
		this.mTitle = title;
		getActionBar().setTitle(this.mTitle);
	}
}
